<template>
  <div class="home">
    <div class="head">
      <van-nav-bar title="订单结算" left-arrow>
        <template #left>
          <Back />
        </template>
      </van-nav-bar>
    </div>
    <div class="content-box">
      <div class="sel-address" @click="isSelectAddress = true">
        <div class="cell">
          <van-cell
            is-link
            :title="list.length > 0 ? '选择地址' : '新增地址'"
          />
        </div>
        <div class="address">
          <p>
            <span class="user-name">{{ defaultAddress.name }}</span>
            <span class="user-tel">{{ defaultAddress.tel }}</span>
            <span class="isDefault" v-if="defaultAddress.isDefault">
              默认
            </span>
          </p>
          <p>{{ defaultAddress.address }}</p>
        </div>
      </div>
      <div class="order-message">
        <div class="title">订单信息</div>
        <OrderItem v-for="(v, i) in orderList" :key="i" :mes="v" />

        <van-empty
          description="没有订单了"
          v-if="orderList.length === 0 ? true : false"
        />
      </div>
      <OrderBottom :shop-arr="orderList" :time="addTime" ref="orderBottomRef" />
    </div>
    <div class="bottom-button-box">
      <van-button
        size="large"
        color="rgb(12,52,186)"
        round
        @click="isShowKeyboard = true"
      >
        模拟结算
      </van-button>
    </div>

    <div class="key-box" v-show="isShowKeyboard">
      <div class="key-title">请输入支付密码123456</div>
      <van-password-input
        :value="keyNum"
        :focused="isShowKeyboard"
        @focus="isShowKeyboard = true"
      />
      <!-- 数字键盘 -->
      <van-number-keyboard
        v-model="keyNum"
        :show="isShowKeyboard"
        @blur="isShowKeyboard = false"
        @input="methods.onInputKey"
      />
    </div>

    <van-action-sheet v-model:show="isSelectAddress" title="选择地址">
      <div class="content">
        <van-address-list
          v-model="chosenAddressId"
          :list="list"
          default-tag-text="默认"
          @add="methods.onAddAddress"
          @select="methods.onSelect"
        />
      </div>
    </van-action-sheet>
  </div>
</template>

<script lang="ts" setup>
import OrderBottom from '@/components/OrderBottom.vue'
import OrderItem from '@/components/OrderItem.vue'
import Back from '@/components/Back.vue'
import {
  AddressListAddress,
  closeToast,
  showLoadingToast,
  showToast
} from 'vant'
import { GET, postFormData } from '@/api'
import { onMounted, ref, useTemplateRef } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'

const router = useRouter()
const route = useRoute()

const orderList = ref<Record<string, any>[]>([])
const defaultAddress = ref({} as AddressListAddress)
const addressList = ref<Record<string, any>[]>([])
const isSelectAddress = ref(false)
const chosenAddressId = ref('0')
// const now = new Date().getTime()
const list = [] as AddressListAddress[]
let ids = ''
const addTime = ref('')
const keyNum = ref('')
const defaultKey = '123456'
const isShowKeyboard = ref(false)

const orderBottomRef: any = useTemplateRef('orderBottomRef')

const methods = {
  getOrderList(ids) {
    GET({
      url: '/order/confirm',
      params: {
        ids
      }
    })
      .then((res) => {
        if (res.data?.list?.length > 0) {
          orderList.value = res.data.list.map((v) => ({
            ...v,
            image_url: import.meta.env.VITE_APP_PROXY_URL + v.image_url
          }))
          addTime.value = dayjs(res.data.list[0].updated_at).format(
            'YYYY-MM-DD HH:mm:ss'
          )
        }
      })
      .catch((err) => {
        console.error(err)
      })
  },
  getAddress() {
    GET({
      url: '/address/list',
      params: {}
    })
      .then((res) => {
        addressList.value = res.data.list
        const arr = res.data.list
        arr.forEach((v) => {
          if (v.is_default) {
            defaultAddress.value = {
              ...v,
              name: v.user_name,
              tel: v.phone,
              address:
                v.province === v.city
                  ? `${v.province}${v.district}${v.detail_address}`
                  : `${v.province}${v.city}${v.district}${v.detail_address}`
            }

            chosenAddressId.value = v.id
          }
          list.push({
            id: v.id,
            name: v.user_name,
            tel: v.phone,
            address:
              v.province === v.city
                ? `${v.province}${v.district}${v.detail_address}`
                : `${v.province}${v.city}${v.district}${v.detail_address}`,
            isDefault: v.is_default === 1 ? true : false
          })
        })
      })
      .catch((err) => {
        console.error(err)
      })
  },
  onAddAddress() {
    router.push({ name: 'NewAddress' })
  },
  onSelect(item: AddressListAddress) {
    defaultAddress.value = item
    isSelectAddress.value = false
  },
  onSettleAccounts() {
    if (defaultAddress.value.address) {
      if (orderList.value.length > 0) {
        postFormData({
          url: '/order/add',
          params: {
            ids,
            phone: defaultAddress.value.tel,
            address: defaultAddress.value.address,
            receiver: defaultAddress.value.name,
            total_price: orderBottomRef.value?.getTotalPrice?.()
          }
        })
          .then(() => {
            router.push({ name: 'MyOrder' })
          })
          .catch((err) => {
            console.error(err)
          })
      } else {
        showToast('请添加订单')
      }
    } else {
      showToast('请选择地址')
    }
  },
  onInputKey(val) {
    keyNum.value += val

    if (keyNum.value.length === 6) {
      isShowKeyboard.value = false
      showLoadingToast({
        message: '正在支付中...',
        forbidClick: true,
        duration: 0
      })
      setTimeout(() => {
        closeToast() //判断密码是否一致
        if (keyNum.value === defaultKey) {
          keyNum.value = ''
          methods.onSettleAccounts()
        } else {
          keyNum.value = ''
          showToast('结算失败，密码错误')
        }
      }, 2000)
    }
  }
}

onMounted(() => {
  ids = (route.query.ids ?? '') as string
  methods.getOrderList(ids)
  methods.getAddress()
})
</script>

<style lang="less" scoped>
.home {
  background-color: rgb(245, 245, 245);
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.head {
  width: 100%;
  position: sticky;
  top: 0;
}
.content-box {
  padding: 10px 20px 100px;
  overflow: auto;
  flex: 1;
  background-color: transparent;
  .sel-address {
    width: 100%;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    overflow: hidden;
    .cell {
      padding-right: 224px;
      background-color: #fff;
    }
    .address {
      font-size: 14px;
      padding: 10px 16px;
      background-color: #fff;
      p {
        margin: 6px 0;
      }
      span {
        margin-right: 20px;
      }
      .user-name {
        color: rgb(12, 52, 186);
      }
      .isDefault {
        color: #fff;
        text-align: center;
        padding: 2px 8px;
        background-color: rgb(12, 52, 186);
        border-radius: 10px;
        display: inline-block;
      }
    }
  }
  .order-message {
    margin-top: 20px;
    padding: 10px 0;
    font-size: 14px;
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
    background-color: #fff;
    .title {
      padding-left: 16px;
    }
  }
}
.bottom-button-box {
  width: 100%;
  overflow: hidden;
  box-sizing: border-box;
  background-color: #fff;
  padding: 10px;
}
:deep(.van-address-list) {
  padding: 0;
}
.content {
  padding: 16px 16px 160px;
}
:deep(.van-address-item__edit) {
  display: none;
}
:deep(.van-address-item__tag) {
  background-color: rgb(12, 52, 186);
}
:deep(.van-address-item) .van-radio__icon--checked .van-icon {
  background-color: rgb(12, 52, 186);
  border-color: rgb(12, 52, 186);
}
:deep(.van-button--danger) {
  background-color: rgb(12, 52, 186);
  border-color: rgb(12, 52, 186);
}
.key-box {
  width: 100%;
  position: fixed;
  bottom: 250px;
  background-color: rgb(242, 243, 245);
  z-index: 19;
  .key-title {
    text-align: center;
  }
}
</style>
